#!/usr/bin/python
'''
Created on 21 Oct 2011

@author: rx201
'''
import settings
from django.core.management import setup_environ
setup_environ(settings)

from apk.models import App, AppStatus
from subprocess import Popen
from apk.apkstorage import *

from django.core.management import setup_environ

Attach_Script = "/home/rx201/aurasium/code/pyAPKRewriter/attach.sh"


def debug_print(str):
    print str
    
def process():
    pendings = App.objects.filter(status = AppStatus.STATUS_Uploaded)
    for apk in pendings:
        debug_print(apk.filename)
        
        flog = open(getLogFilePath(apk), "w")
        flog.write(apk.filename)
        worker = Popen([Attach_Script, getUploadedAPKPath(apk), getProcessedAPKPath(apk)], stdout = flog, stderr = flog)
        rtnval = worker.wait()
        flog.close()
        
        if rtnval == 0 and os.path.exists(getProcessedAPKPath(apk)):
            apk.status = AppStatus.STATUS_Processed
            debug_print("succeed.")
        else:
            apk.status = AppStatus.STATUS_Failed
            debug_print("failed.")
        apk.save()
        
    
    
if __name__ == "__main__":
    process()